<template>
	<Form :model="formItem" :label-width="120">
		<div class="list">
      <Card>
        <div class="tabs_container">
          <Row>
            <Col span="14">
                <div class="tabs_box">
                    <Row>
                        <ul class="tabs_list">
                            <li v-for="(tab, index) in tabs" :class="{active: index==num}" @click="toggle(index,tab)" :key="index">
                            <Dropdown trigger="click" :class="{active: index==num}" @mouseover="toggle(index)">
                                    <span>
                                        {{tab.name}}
                                        <Icon type="ios-arrow-down"  v-if="index > 0"></Icon>
                                    </span>
                                    <DropdownMenu slot="list" v-if="index > 0">
                                        <DropdownItem @click.native="modal6=true">编辑</DropdownItem>
                                        <DropdownItem @click.native="modal7=true">删除</DropdownItem>
                                    </DropdownMenu>
                            </Dropdown>
                            </li>
                            <div class="clear"></div>
                        </ul>
                        <div class="clear"></div>
                    </Row>
                </div>
            </Col>
            <Col span="6" push="7">
							<Input v-model="formItem.name" style="width:150px" placeholder="请输入营销活动名称">
								<Button slot="append" icon="ios-search" @click="queryTableList()"></Button>
							</Input>
						</Col>
            <Col span="2" pull="2">
							<Button type="success" @click="addOpen"> <Icon type="plus"></Icon>新增营销活动</Button>
						</Col>
						<Col span="2" pull="6">
							<Button type="success" @click="modal1 = true"> <Icon type="plus"></Icon>新增分类</Button>
						</Col>
          </Row>
          <Row>
            <Col>
              <Table :loading="TableLoading" border :columns="columns1" :data="listData"></Table>
            </Col>
          </Row>
          <Row type="flex" justify="center" style="margin-top:2vh;">
            <Col>
              <Page :id="pageId" show-total :total="total" :page-size="pageSize" @on-page-size-change="changegroupPageSize" @on-change="pageable" show-sizer show-elevator></Page>
            </Col>
            <Col push="1">
              <Button style="margin-top: 6px;" type="primary" @click="goElevatorPage(pageId)">跳转</Button>
            </Col>
          </Row>
        </div>
      </Card>
      <Modal
          v-model="modal1"
          title="新建分类"
          @on-ok="addItem"
          >
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidates" :label-width="80">
            <FormItem label="分类名称:" prop="name">
                <Input v-model="formValidate.name" :maxlength=8 placeholder="请输入分类名称,最多8位" style="width:90%;" clearable></Input>
            </FormItem>
          </Form>
      </Modal>
      <Modal
          v-model="modal2"
          title="提示信息"
          @on-ok="remove"
          >
          <h3>确定删除分组XXX？</h3>
      </Modal>
      <Modal
          v-model="modal3"
          title="复制分组"
          >
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidates" :label-width="100">
            <FormItem label="人群名称:" prop="copygroupname">
                <Input v-model="formValidate.copygroupname" placeholder="请输入分类名称" style="width:200px;" clearable></Input>
            </FormItem>
            <FormItem label="选择人群分类:" prop="grouptype" style="margin-top:4vh;" :label-width="100">
              <Select v-model="formValidate.grouptype" placeholder="请选择..." style="width:200px;"  clearable>
                  <Option value="VIP1">面乳活跃人群1</Option>
                  <Option value="VIP2">面乳活跃人群2</Option>
              </Select>
            </FormItem>
          </Form>
      </Modal>
      <Modal
          v-model="modal4"
          title="移动分组"
          >
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidates" :label-width="100">
            <FormItem label="选择人群分类:" prop="movegroup" style="margin-top:4vh;" :label-width="100">
              <Select v-model="formValidate.movegroup" placeholder="请选择..." style="width:200px;"  clearable>
                  <Option value="movegroup">面乳活跃人群1</Option>
                  <Option value="movegroup">面乳活跃人群2</Option>
              </Select>
            </FormItem>
          </Form>
      </Modal>
      <Modal                      
          v-model="modal5"
          title="编辑分组"
          >
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidates" :label-width="100">
            <FormItem label="分组名称:" prop="editgroup">
                <Input v-model="formValidate.editgroup" placeholder="请输入分类名称" style="width:90%;margin-bottom:2vh;" clearable></Input>
            </FormItem>
            <FormItem label="分组类型:" prop="typegroup">
                <Input v-model="formValidate.typegroup" placeholder="请输入分类名称" style="width:90%;margin-bottom:2vh;" clearable></Input>
            </FormItem>
            <FormItem label="人群总数:" prop="totalgroup">
                <Input v-model="formValidate.totalgroup" placeholder="请输入分类名称" style="width:90%;margin-bottom:2vh;" clearable></Input>
            </FormItem>
            <FormItem label="状态:" prop="status">
              <Select v-model="formValidate.status" placeholder="请选择..." style="width:90%;margin-bottom:2vh"  clearable>
                  <Option value="movegroup">计算完成</Option>
                  <Option value="movegroup2">计算中</Option>
              </Select>
            </FormItem>
            <FormItem label="创建时间:" prop="creategrouptime">
                <Input v-model="formValidate.creategrouptime" placeholder="请输入分类名称" style="width:90%;margin-bottom:2vh;" clearable></Input>
            </FormItem>
            <FormItem label="创建人:" prop="creater">
                <Input v-model="formValidate.creater" placeholder="请输入分类名称" style="width:90%;margin-bottom:2vh;" clearable></Input>
            </FormItem>
          </Form>
      </Modal>
      <Modal
          v-model="modal6"
          title="修改分类"
          @on-ok="editItem(num)"
          >
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidates" :label-width="80">
            <FormItem label="分类名称:" prop="edittabsnameInput">
                <Input v-model="formValidate.edittabsnameInput" clearable placeholder="请输入分类名称,字数不超过8位" :maxlength=8 style="width:90%;"></Input>
            </FormItem>
          </Form>
      </Modal>
      <Modal
          v-model="modal7"
          title="提示信息"
          @on-ok="handleTabRemove(num)"
          >
          <h3>确定删除该分类吗？</h3>
      </Modal>
			<!-- 移动 -->
			<Modal v-model="testModal" v-if='DateReady' title="移动分类" width="650" :mask-closable="false">
				<Form :label-width="120">
					<Form-item label="选择营销分类">
						<Select v-model="toCampaignCategory" placeholder="请选择"  clearable>
							<Option v-for="(item,index) in marketActivityList" :key="index" :value="item.id">{{item.name}}</Option>
						</Select>
					</Form-item>
				</Form>
				<div slot="footer">
					<i-button type="primary" size="large" long :loading="loading" @click="moveCampaignCategory()" icon="checkmark-round">保存</i-button>
				</div>
			</Modal>
		</div>
	</form>
</template>
<script>
import TableExpand from "./TableExpand";

import { fetchMarketingList,fetchmarketactvityList,fetchmarketMoveCategory,fetchmarketCampaignCategoryAll,
  fetchmarketAddCampaignCategory,fetchmarketDelCampaignCategory,fetchmarketEditCampaignCategory,
  fetchmarketEditCampaignCategoryId,fetchmarketEditCampaignStatus,fetchmarketDelCampaign } from '@/api/marketing'
export default {
  name: "list",
  components: {},
  data() {
    return {
      pageId:"targetPage",
      toCampaignCategory:"",
      SelectMarketing: "",
      currIndex: 0, // 当前编辑和新增的行号
      TableLoading: false, // 分页loading
      tableSize: "small", // @:size
      DateReady: false, // 判断异步数据加载完成，避免报错
      loading: false, // save
      currIndex: 0,
      saveDisabled: false,
      listData: [],
      marketActivityList: [],
      marketbatchList:[],
      campaignId:'',  // 移动分类活动ID
      campaignCategoryId:0,   //移动营销分类id
      current: 1,
      total:0,
      totalSize: 0, //总条数
      pageNum: 1, //开始条数
      pageSize: 10, //每页记录数
      tabs:[{"name":"默认分类","id":null}],
      num: 0,
      modal1: false,
      modal2: false,
      modal3: false,
      modal4: false,
      modal5: false,
      modal6: false,
      modal7: false, 

      formValidate:{
        name:'',
        content:'',
        copygroupname:'',
        grouptype:'',
        movegroup:'',
        editgroup:'',
        typegroup:'',
        totalgroup:'',
        status:'',
        creategrouptime:'',
        creater:'',
        addtabsname:[],
        tabItem:'',
        edittabsnameInput:'',
      },

      ruleValidates:{
            name: [
                { required: true, message: '分类名称不能为空!', trigger: 'blur' }
            ],
            content: [
                { required: true, message: '分类内容不能为空！', trigger: 'blur' }
            ],
            copygroupname: [
                { required: true, message: '人群名称不能为空!', trigger: 'blur' }
            ],
            tabItem: [
                { required: true, message: '分类名称不能为空!', trigger: 'blur' }
            ],
            edittabsnameInput: [
                { required: true, message: '分类名称不能为空!', trigger: 'blur' }
            ],
        },

      formItem: {
        name: ""
      },

      testModal: false,
      select: '',
      columns1: [
        //列表表头
        {
          type: "expand",
          width: 50,
          render: (h, params) => {
            if(params.row && params.row.campaignInsts
                  && params.row.campaignInsts.length>0)
            return h(TableExpand, {
              props: {
                row: params.row
              }
            });
          }
        },
        {
          title: "营销活动名称",
          key: "name",
          align: "center",
          width:150
        },
        {
          title: "活动状态",
          key: "status",
          align: "center",
          width:150,
          render: (h, params) => {
            const type = params.row.status === 1 ? "success" : "error";
            let _this = this;
            let text = "";
            let color = "";
            if (params.row.status == 0) {
              text = "删除";
              color = "red";
            } else if (params.row.status == 1) {
              text = "创建中";
              color = "lightorange";
            } else if (params.row.status == 2) {
              text = "进行中";
              color = "lightskyblue";
            } else if (params.row.status == 3) {
              text = "已完成";
              color = "lightgreen";
            }
            const row = params.row;
            return h(
              "Tag",
              {
                props: {
                  type: "dot",
                  color: color
                }
              },
              text
            );
          }
        },
        {
          title: "活动开始时间",
          key: "start_time",
          align: "center",
          width:170
        },
        {
          title: "下批次发送时间",
          key: "next_run_time",
          align: "center",
          width:170
        },
        {
          title: "活动结束时间",
          key: "end_time",
          align: "center",
          width:170
        },
        {
          title: "累计短信触达人数",
          key: "total_sms_count",
          align: "center",
          width:150
        },
        {
          title: "累计微信触达人数",
          key: "total_wx_count",
          align: "center",
          width:150
        },
        {
          title: "累计权益触达人数",
          key: "total_coupon_count",
          align: "center",
          width:150
        },
        {
          title: "创建人",
          key: "username",
          align: "center",
          width:150
        },
        {
          title: "操作",
          key: "actor",
          align: "center",
          width: 300,
          render: (h, params) => {
            var status = params.row.status;
                  if(status ==1 ) return h("div", [
                    h(
                      "Button",
                      {
                        props: {
                          type: "primary",
                          size: "small"
                        },
                        style: {
                          marginRight: "3px"
                        },
                        on: {
                          click: () => {
                            this.editOpen(params.row.id);
                          }
                        }
                      },
                      "编辑"
                    ),

                    h(
                      "Button",
                      {
                        props: {
                          type: "error",
                          size: "small"
                        },
                        style: {
                          marginRight: "3px"
                        },
                        on: {
                          click: () => {
                            this.remove(params.row);
                          }
                        }
                      },
                      "删除"
                    ),
                    h(
                      "Button",
                      {
                        props: {
                          type: "error",
                          size: "small"
                        },
                        style: {
                          marginRight: "3px"
                        },
                        on: {
                          click: () => {
                            this.changeStatus(params.row,2);//启动
                          }
                        }
                      },
                      "启动"
                    ),
                    h(
                      "Button",
                      {
                        props: {
                          type: "info",
                          size: "small"
                        },
                        style: {
                          marginRight: "3px"
                        },
                        on: {
                          click: () => {
                            this.moveOpen(params);
                          }
                        }
                      },
                      "移动"
                    )
                  ]);
                  if(status ==2 ) return h("div", [
                    h(
                      "Button",
                      {
                        props: {
                          type: "info",
                          size: "small"
                        },
                        style: {
                          marginRight: "3px"
                        },
                        on: {
                          click: () => {
                            this.report(params.row.id);
                          }
                        }
                      },
                      "效果报告"
                    ),
                    h(
                      "Button",
                      {
                        props: {
                          type: "error",
                          size: "small"
                        },
                        style: {
                          marginRight: "3px"
                        },
                        on: {
                          click: () => {
                            this.changeStatus(params.row,1);//停止
                          }
                        }
                      },
                      "停止"
                    )
                  ]);
                  if(status ==3 ) return h("div", [
                    h(
                      "Button",
                      {
                        props: {
                          type: "info",
                          size: "small"
                        },
                        style: {
                          marginRight: "3px"
                        },
                        on: {
                          click: () => {
                            this.report(params.row.id);
                          }
                        }
                      },
                      "效果报告"
                    )
                  ]);
          }
        }
      ]
    };
  },
  watch: {
    params: {
      handler(val) {
        this.updateTableList(val);
      },
      deep: true
    },
    SelectMarketing: {
      handler(val) {
        switch (val) {
          case "1":
            this.campaignCategoryId = val
            this.updateTableList();
            break;
          case "2":
            this.campaignCategoryId = val
            this.updateTableList();
            break;
          case "3":
            this.campaignCategoryId = val
            this.updateTableList();
            break;
        }
      }
    }
  },
  computed: {
    state() {
      return this.$store.state.app;
    }
  },
  methods: {
    goElevatorPage(pageId){
      var evtObj;
      var thisPage=document.getElementById(pageId);
      var elevatorDiv=thisPage.getElementsByClassName("ivu-page-options-elevator");
      if(elevatorDiv && elevatorDiv.length>0){
        var pageInput = elevatorDiv[0].getElementsByTagName("input")[0];
        if (window.KeyEvent) {//firefox 浏览器下模拟事件
          evtObj = document.createEvent('KeyEvents');
          evtObj.initKeyEvent("keyup", true, true, window, true, false, false, false, 13, 0);
        } else {//chrome 浏览器下模拟事件
          evtObj = document.createEvent('UIEvents');
          evtObj.initUIEvent("keyup", true, true, window, 1);
          delete evtObj.keyCode;
          if (typeof evtObj.keyCode === "undefined") {//为了模拟keycode
            Object.defineProperty(evtObj, "keyCode", { value: 13 });
          } else {
            evtObj.key = String.fromCharCode(13);
          }
        }
        pageInput.dispatchEvent(evtObj);
      }
    },
    //搜索
    queryTableList() {
      this.updateTableList(this.params);
    },

    //分页
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.updateTableList();
    },

     changegroupPageSize(pageSize){
      this.pageNum = 1,
      this.pageSize = pageSize;
      this.updateTableList();
    },

    changeCurrent(current) {
      this.start = current * this.limit - this.limit;
      this.updateTableList();
    },

    //请求默认分组表格数据
    updateTableList(params) {
      this.TableLoading = true;
      this.load = true;
      var reqParams = {
        pageNum:this.pageNum,
        pageSize:this.pageSize,
        campaignCategoryId:this.campaignCategoryId
      };
      if(this.formItem.name){
        reqParams.name = this.formItem.name;
      }
      fetchMarketingList(reqParams).then(res=>{
          this.TableLoading = false;
          if (res.data.code == 200) {
            this.listData = res.data.result.campaignPage.records;
            this.pageNum = res.data.result.campaignPage.current;
            this.pageSize = res.data.result.campaignPage.size;
            this.total = res.data.result.campaignPage.total;
            this.campaignId = res.data.result.campaignPage.records.id;
            this.DateReady = true;
            this.TableLoading = false;
          }
      })
      .catch(error=>{
        this.$Message.error(error);
      })
    },

    // 请求营销活动分类下拉列表
    FetchmarketactvityList() {
      fetchmarketactvityList().then(res => {
          this.TableLoading = false;
          if (res.data.code == 200) {
            this.marketActivityList = res.data.result.campaignCategoryList;
            this.campaignCategoryId = res.data.result.campaignCategoryList.id;
          } else {
            this.$Message.error(res.msg);
          }
        }
      );
    },

    fetchmarketCampaignCategoryAll(params) {
      //查询营销人群类别tabs
      var reqParams = {
        page: this.page,
        limit: this.limit,
        total: this.total
      };
      fetchmarketCampaignCategoryAll(reqParams).then(res => {
          if (res.data.code == 200 && res.data.result && res.data.result.campaignCategoryList) {
            var tab = {
              name:'默认分类',
              id:null
            }
            var tabArr = [];
            tabArr.push(tab);
            this.tabs = tabArr.concat(res.data.result.campaignCategoryList);
            if(this.campaignCategoryId == 0 && this.tabs.length > 0){
              this.campaignCategoryId = this.tabs[0].id;
              this.updateTableList();
            }
          }
        })
        .catch(error => {
          this.$Message.error(error);
        });
    },

    //删除
    remove(params) {
      var my = this;
      this.$Modal.confirm({
        title: "删除确认",
        content: `是否确认删除此条记录`,
        onOk: function() {
          this.$Loading.start();

          var reqParams = {
            id: params.id
          };
          fetchmarketDelCampaign(reqParams).then(res => {
            if (res.data.code == 200) {
              this.$Message.info("删除成功！")
              my.updateTableList();
            }else{
                this.$Message.info("删除失败："+res.data.msg);
            }
          })
        }
      });
    },

    //更改状态
    changeStatus(params,status) {
      var my = this;
      this.$Modal.confirm({
        title: "更改状态",
        content: `是否确认更改状态`,
        onOk: function() {
          var reqParams = {
            campaignId: params.id,
            status:status
          };
          fetchmarketEditCampaignStatus(reqParams).then(res => {
            if (res.data.code == 200) {
              my.updateTableList();
              if(status == 2){
                this.$Message.info("启动成功！")
              }else if(status == 3){
                this.$Message.info("停止成功！")
              }
            }else{
              if(status == 2){
                this.$Message.info("启动失败："+res.data.msg);
              }else if(status == 3){
                this.$Message.info("停止失败："+res.data.msg);
              }
            }
          })
        }
      });
    },

    //移动分类
    moveOpen(params) {
      this.campaignId = params.row.id;
      this.DateReady = true;
      this.testModal = true;
      this.loading = false;
      this.FetchmarketactvityList();
    },
    moveCampaignCategory() {
      var reqParams = {
        campaignId: this.campaignId,
        campaignCategoryId: this.toCampaignCategory
      };
      fetchmarketEditCampaignCategoryId(reqParams).then(res => {
        this.updateTableList();
        if (res.data.code == 200) {
          this.updateTableList();
          this.testModal = false;
        }else{
          this.$Message.error(res.data.msg);
        }
      })
    },

    addOpen() {
      this.$router.push({path: "/static/marketingManagementAdd"});
    },

    editOpen(params){
      this.$router.push({path: "/static/marketingManagementEdit/"+ params,
        query: { _button: true,}});
    },

    report(params){
      this.$router.push({path: "/static/marketingReport/"+ params });
    },
    toggle(index,tab){
      this.pageNum = 1;
      this.num = index;
			this.campaignCategoryId = tab.id;
			this.formValidate.edittabsnameInput = tab.name;
      this.updateTableList();
    },
    pageable(current) {
        this.pageNum = current;
         this.updateTableList();
    },
    addItem(){  // 添加分类
      var reqParams = {
          name : this.formValidate.name
      }
      fetchmarketAddCampaignCategory(reqParams).then(res => {
            if (res.data.code == 200 ) {
              if(res.data.result){
                reqParams.id = res.data.result;
              }
              this.tabs.push(reqParams);
              this.formValidate.name = ''; 
              this.modal1 = false;
            } else {
              this.$Message.error(res.data.msg);
              this.modal1 = true;
            }
          }
        );
    },
    handleTabRemove (num) {
      var my = this;
      var reqParams={
        campaignCategoryId:this.campaignCategoryId
      }
      if(this.num == 0 || !this.campaignCategoryId){
        this.$Message.error('不能删除默认分类')
      }else{
        fetchmarketDelCampaignCategory(reqParams).then(res => {
            if (res.data.code == 200) {
              this.tabs.splice(num,1);
              this.$Message.info("分类删除成功");
              my.updateTableList();
            } else {
              this.$Message.error(res.data.msg);
            }
          }
        );


      }
    },
    editItem(num,value){
      var reqParams = {
        name:this.formValidate.edittabsnameInput,
        id:this.campaignCategoryId
      }
      fetchmarketEditCampaignCategory(reqParams).then(res => {
          if (res.data.code == 200) {
            this.tabs[num].name = this.formValidate.edittabsnameInput;
            this.modal6 = false;
          } else {
            this.$Message.error(res.data.msg);
            this.modal6 = true;
          }
        }
      );

    }
  },
  created() {
    this.fetchmarketCampaignCategoryAll();
    //this.updateTableList(this.params);
  }
};
</script>

<style lang="less" scoped>
.search-filter {
  opacity: 0;
  display: none;
  overflow: hidden;
  transition: all 0.28s ease-out;
  &.active {
    opacity: 1;
    display: block;
  }
}
 .tabs_container{   //tabs
   width:100%;
   padding-bottom: 2vh;
   background-color: #fff;
   .tabs_box{
       width: 100%;
       .tabs_list{
          width:50vw;
          height: 7vh;
          border-bottom:1px solid #ccc;
          display: flex;
          flex-wrap: nowrap;
          overflow-x: auto;
          overflow-y: hidden;
           li{
               display: block;
               float: left;               
               min-width: 15vw;
               height: 5vh;
               font-size: 14px;
               color: #333;
               line-height: 30px;
               text-align: center;
               &:hover{
                   cursor: pointer;
               }
               .active{
                    min-width: 9vw;
                    color: lightskyblue;
                    border-bottom:5px solid lightskyblue;
                }
            }
            
       }
       .add_btn{
           width:6vw;
           height: 5vh;
           float: right;
           margin-right: 1%;
           margin-top: -8vh;
       }
   }
   .content{
       width: 100%;
      
   }
 }
</style>
